import pymysql
import requests
import yaml
from string import Template
import time
from jsonschema import validate
from utils.logger import get_logger


class BaseApi:

    def send(self, req):
        """
        发送请求
        :param req:传入的参数
        :return: 响应结果
        """
        self.logger.info('请求参数：{}'.format(req))
        r = requests.request(**req)
        return r

    def general_assert(self, response):
        """
        通用断言
        :param response: 返回参数
        :return:
        """
        self.logger.info('返回参数：{},返回code：{}'.format(response.text, response.status_code))
        assert response.status_code == 200

    def req(self, data: dict):
        """
        将传入的参数的url进行拼接
        :param data: 未拼接的参数字典
        :return: 拼接后的参数
        """

        with open('../conf/env.yml', 'r') as f:
            envs = yaml.safe_load(f)
        data['url'] = envs['env'][envs['default']] + data['url']
        return data

    def template(self, filename, data: dict):
        '''
        参数替换
        :param filename: 需替换的yaml文件
        :param data: 需替换的参数
        :return: 原本yaml文件替换过后所对应的python object
        '''

        with open(filename, 'r')as f:
            tem = Template(f.read())
            result = tem.substitute(name=f.read(), **data)
            return yaml.safe_load(result)

    def timestamp(self):
        """
        获取当前时间戳
        :return: 当前时间戳
        """
        return int(time.time())

    def verify(self, yaml_schema_file, response_data: dict):
        """
        校验返回结果的数据结构是否对应
        :param yaml_schema_file: yaml文件，存储在schema目录下
        :param response_data: 接口返回的数据
        :return:
        """
        a = yaml.safe_load(open(yaml_schema_file, 'r', encoding='utf-8'))
        validate(instance=response_data, schema=a)

    # 执行数据库操作,需要在内网环境操作
    def db(self, sql: str):
        """
        数据库操作
        :param sql:需执行的sql语句
        :return: 执行后的结果，为元组类型
        """
        db_conf = yaml.safe_load(open('../conf/database.yml'))
        db = pymysql.Connect(**db_conf)
        cursor = db.cursor()
        try:
            cursor.execute(sql)
            db.commit()

        except Exception as e:
            raise Exception(e)
        else:
            try:
                # data1=cursor.fetchone()#返回第一行
                data2 = cursor.fetchall()  # 返回所有结果
                return data2
            except Exception as e1:
                raise Exception(e1)
        finally:
            cursor.close()

    def get_token(self):
        sql = 'SELECT auth_key FROM `user` WHERE moego_code is NOT NULL LIMIT 1'
        out = self.db(sql)[0][0]
        return out


if __name__ == '__main__':
    # req = {'method': 'get',
    #        'url': '/1.txt',
    #        }
    # re = {'other': 'test',
    #       'other1': 'test1'
    #
    #       }
    a = BaseApi()
    # b = a.template('../data/get_test1.yaml', data=re)
    # print(a.template('../data/get_test1.yaml', data=re))
    # print(type(b))
    # # b = a.req(req)
    # # print(b)
    sql = 'SELECT auth_key FROM `user` WHERE moego_code is NOT NULL LIMIT 2'
    token = a.get_token()
    print(token)
